const API = require('../../pages/api/index')
const {
  typeJson
} = require('../../utils/typejson')
let prolist = wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist'))
const {
  get,
  post
} = require('../../request/index')


Page({

  /**
   * 页面的初始数据
   */
  data: {
    pulldown: "",
    pullup: 2,
    addButton: true,
    show: false,
    prolist: wx.getStorageSync('prolist') == '' ? wx.getStorageSync('prolist') : JSON.parse(wx.getStorageSync('prolist')),

    mainActiveIndex: 0,
    activeId: [],
    activeIdPopup: [],
    max: 1,
    deptTreeList: [],
    wuanpoplist: [],
    flowDetails: [],
    usingUnit: [],
    wuanlist: [],
    category:null,
    desci: null, //         发现问题
    position: null, //    隐患部位
    photo: null, //     隐患图片
    limitedTime: null, //    datetime类型  整改期限
    level: null, //     int           隐患等级 隐患等级(1是一级隐患，2是重大隐患)
    remark: null, //     备注
    inspectedUsers: null, //   检查人（数组存储）
    bgColor: "#ccc",
    klit: [],
    opId: null,
    steps: [{
        text: '步骤一',
        desc: '数据录入',
      },
      {
        text: '步骤二',
        desc: '选择审批人',
      },
      {
        text: '步骤三',
        desc: '发起审核',
      }
    ],
    names: "",
    jsonType: [{
        label: "一般隐患",
        value: 1
      },
      {
        label: "重大隐患",
        value: 2
      },


    ],
    people: [],
    titleName:""
  },
  onChangegroup(event) {

    this.setData({
      people: event.detail,
    });
  },
  changeTime1(e) {
    this.setData({
      limitedTime: e.detail
    })
  },
  changeTime2(e) {
    this.setData({
      endTime: e.detail
    })
  },
  bindinput(e) {
    console.log(e);
    this.setData({
      [e.currentTarget.dataset.num]: e.detail.value
    })
  },
  changeSelect(e) {
    this.setData({
      level: e.detail
    })
  },
  selent() {
    this.setData({
      show1: true
    })
  },
  onClose() {
    this.setData({
      show: false,
      show1: false,
    });
  },
  changeUpint(e) {
    this.setData({
      photo: e.detail,
    });
  },
  onChange(event) {

    this.setData({
      usingUnit: event.detail,
    });
  },
  submit() {
    let {
      desci, //         发现问题
      position, //    隐患部位
      photo, //     隐患图片
      limitedTime, //    datetime类型  整改期限
      level, //     int           隐患等级 隐患等级(1是一级隐患，2是重大隐患)
      remark, //     备注
      inspectedUsers, //   检查人（数组存储）
      prolist,
      flowDetails,
      category,
      people
    } = this.data;
    flowDetails.forEach((item, index) => {
      item.sort = index + 1;
      delete item.name;
    })

    post('/app/dangerhidden', {
      desci, //         发现问题
      position, //    隐患部位
      photo, //     隐患图片
      limitedTime, //    datetime类型  整改期限
      level, //     int           隐患等级 隐患等级(1是一级隐患，2是重大隐患)
      remark, //     备注
      inspectedUsers:people.toString(), //   检查人（数组存储）
      flowDetails, //审核人列表
      type: 5,
      userId: prolist.userId, //用户id
      category: category,
      flag:0

    }).then(res => {

      if (res.code == 200) {

        wx.showToast({
          title: '提交成功',
          duration: 3000,
          icon: 'success',
          mask: true
        })
        wx.navigateTo({
          url: '/pages/dangerRecord/dangerRecord',
        })
      }
    })

  },
  nextStep() {
    this.setData({
      show: true,
      flowDetails: [],
      wuanpoplist: []
    });

  },
  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },
  onChangeInput(e) {
    this.setData({
      [e.target.dataset.lable]: e.detail
    })
  },

  onClickNav({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },

  onClickItem({
    detail = {}
  }) {
    console.log(detail);
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({
      activeId,
      usingUnit: [],
      show1: false,
      names: detail.text
    });
    this.postbalstWork(activeId)

  },

  cross(e) {
    let {
      flowDetails
    } = this.data
    console.log(e.currentTarget.dataset.user);
    flowDetails.map(((item, index) => {
      if (item.auditUserId == e.currentTarget.dataset.user) {
        flowDetails.splice(index, 1)
      }
    }))
    this.setData({
      flowDetails: flowDetails
    })
  },
  edit(e) {

    let {
      flowDetails
    } = this.data;
    let {
      userId,
      nickName
    } = e.target.dataset.item

      let flag = true;
      if (flowDetails.length != 0) {
        flowDetails.forEach(item => {
          if (item.auditUserId == userId) {
            flag = false
          }
        });
      }
      if (flag) {
        let obj = {
          auditUserId: userId,
          name: nickName,
        };
        let list = [];

        list.push(obj);


        this.setData({
          flowDetails: flowDetails.concat(list),

        })
      }

    



  },
  onClickPopup({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0,
    });
  },
  onClickItemPopup({
    detail = {}
  }) {
    console.log(detail);
    const activeIdPopup = this.data.activeIdPopup === detail.id ? null : detail.id;
    console.log(activeIdPopup);
    this.setData({
      activeIdPopup,
    });
    this.postbalstWork(activeIdPopup);
  },
  async postbalstWork(activeId) {
    let res = await get(`/system/user/list?deptId=${activeId}&peopleType=1&pageNum=1&pageSize=999`)
    if(res.code==200){
      this.setData({
        wuanlist: res.rows,
        wuanpoplist: res.rows
      })
    }
  },






  /**
   * 生命周期函数--监听页面加载
   */
onLoad(v){
  let obj = wx.getStorageSync('obj') == '' ? wx.getStorageSync('obj') : JSON.parse(wx.getStorageSync('obj'))
  console.log(obj);
 
     this.setData({
       category:Number(obj.category),
       titleName:obj.title
     })
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getDeptTree();
  },

  async getDeptTree() {
    let res = await get('/system/user/deptTree');

    if (res.code == 200) {
      let newJsonParam = JSON.parse(JSON.stringify(res.data).replace(/label/g, "text"));
      this.setData({
        deptTreeList: newJsonParam
      })
    }
  },




  canvasChang(e) {
    console.log(e.detail);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      pullup: this.data.pullup + 1
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})